package com.EAsystem.controller.admin;

import com.EAsystem.annotation.RequireRole;
import com.EAsystem.entity.Course;
import com.EAsystem.entity.CourseSelection;
import com.EAsystem.entity.Student;
import com.EAsystem.service.CourseSelectionService;
import com.EAsystem.service.CourseService;
import com.EAsystem.service.StudentService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
@RequireRole({1}) // 只有管理员可以访问
public class CourseSelectionController {

    @Autowired
    private CourseSelectionService courseSelectionService;
    
    @Autowired
    private CourseService courseService;
    
    @Autowired
    private StudentService studentService;

    /**
     * 管理端 - 选课记录管理页面
     */
    @GetMapping("/course-selection")
    public String adminCourseSelection(@RequestParam(defaultValue = "1") int page,
                                     @RequestParam(defaultValue = "5") int size,
                                     @RequestParam(required = false) Long courseId,
                                     @RequestParam(required = false) Long studentId,
                                     @RequestParam(required = false) String studentSearch,
                                     @RequestParam(required = false) String courseSearch,
                                     Model model) {
        
        PageInfo<CourseSelection> pageInfo;
        
        if (studentId != null) {
            // 按学生查询
            pageInfo = courseSelectionService.findByStudentIdWithPage(studentId.intValue(), page, size);
        } else if (courseId != null) {
            // 按课程查询
            pageInfo = courseSelectionService.findByCourseIdWithPage(courseId.intValue(), page, size);
        } else {
            // 查询所有
            pageInfo = courseSelectionService.findByPage(page, size);
        }
        
        if (pageInfo == null) {
            pageInfo = new PageInfo<>();
        }
        
        // 获取所有课程和学生，用于搜索下拉框
        List<Course> allCourses = courseService.findAll();
        PageInfo<Student> studentPageInfo = studentService.findAllByPage(1, 1000); // 获取足够多的学生
        List<Student> allStudents = studentPageInfo.getList();
        
        model.addAttribute("courseSelections", pageInfo.getList());
        model.addAttribute("allCourses", allCourses);
        model.addAttribute("allStudents", allStudents);
        model.addAttribute("currentPage", page);
        model.addAttribute("pageSize", size);
        model.addAttribute("totalPages", pageInfo.getPages());
        model.addAttribute("totalRecords", pageInfo.getTotal());
        model.addAttribute("searchCourseId", courseId);
        model.addAttribute("searchStudentId", studentId);
        model.addAttribute("studentSearch", studentSearch);
        model.addAttribute("courseSearch", courseSearch);
        
        return "admin/course-selection";
    }

    /**
     * 管理端 - 更新选课状态
     */
    @PostMapping("/course-selection/updateStatus")
    @ResponseBody
    public Map<String, Object> updateCourseSelectionStatus(@RequestParam Long id, 
                                                           @RequestParam Integer status) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String currentTime = sdf.format(new Date());
            
            int updateResult = courseSelectionService.updateStatus(id, status, currentTime);
            
            if (updateResult > 0) {
                result.put("success", true);
                result.put("message", "状态更新成功");
            } else {
                result.put("success", false);
                result.put("message", "状态更新失败");
            }
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "状态更新失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 管理端 - 删除选课记录
     */
    @GetMapping("/course-selection/delete/{id}")
    public String deleteCourseSelection(@PathVariable Long id) {
        courseSelectionService.delete(id.intValue());
        return "redirect:/admin/course-selection";
    }

    /**
     * 管理端 - 批量删除选课记录
     */
    @GetMapping("/course-selection/batchDelete")
    public String batchDeleteCourseSelection(@RequestParam("ids") String ids) {
        if (ids != null && !ids.isEmpty()) {
            for (String id : ids.split(",")) {
                try {
                    courseSelectionService.delete(Integer.valueOf(id));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        }
        return "redirect:/admin/course-selection";
    }

    /**
     * 获取选课详情（Ajax）
     */
    @GetMapping("/course-selection/view/{id}")
    @ResponseBody
    public Map<String, Object> viewCourseSelection(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            CourseSelection courseSelection = courseSelectionService.findById(id.intValue());
            if (courseSelection != null) {
                result.put("success", true);
                result.put("courseSelection", courseSelection);
            } else {
                result.put("success", false);
                result.put("message", "选课记录不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取选课记录失败：" + e.getMessage());
        }
        
        return result;
    }
} 